<?php
namespace App\Supports\File;

use Intervention\Image\Constraint;
use Illuminate\Support\Facades\File;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Storage;
use GuzzleHttp\Client;

class ImageUploader
{
	/**
	 * @var \Intervention\Image\Image
	 */
	protected $image;
	protected $imageName = '';
	protected $imageExtension = '';
	protected $imageFullName = '';
	
	protected $maxWidth = 1080;
	protected $maxHeight = 1080;
	
	protected function setProperties($image)
	{
		$this->image = Image::make($image);
		$this->image->orientate();
		$this->imageName = uniqid(time());
		$this->imageExtension = $image->extension();
		$this->imageFullName = "{$this->imageName}.{$this->imageExtension}";
		
		if (! File::isDirectory(public_path('temp'))) {
			File::makeDirectory(public_path('temp'), 755, true, true);
		}
	}
	
	protected function localFolderPath()
	{
		return public_path("temp");
	}
	
	protected function localFullPath()
	{
		return public_path("temp/{$this->imageFullName}");
	}
	
	protected function remoteFolderPath()
	{
		return "uploads/images/" . date("Ym/d", time());
	}
	
	protected function remoteFullPath()
	{
		return "{$this->remoteFolderPath()}/{$this->imageFullName}";
	}
	
	protected function saveToLocal()
	{

		$width = $this->image->width();
		$height = $this->image->height();
		if ($width > $this->maxWidth) {
			$this->image->resize($this->maxWidth, null, function (Constraint $constraint) {
				$constraint->aspectRatio();
				$constraint->upsize();
			}); 
		}
		if ($height > $this->maxHeight) {
			$this->image->resize(null, $this->maxHeight, function (Constraint $constraint) {
				$constraint->aspectRatio();
				$constraint->upsize();
			});
		}

		
		$this->image->save($this->localFullPath());
	}
	
	protected function saveToRemote()
	{
		Storage::putFileAs($this->remoteFolderPath(), $this->localFullPath(), $this->imageFullName);
		File::delete($this->localFullPath());
		return Storage::url($this->remoteFullPath());
	}
	
	protected function save()
	{
		$this->saveToLocal();
		$res =  $this->saveToRemote();


		/*$url = "http://api-img-bj.fengkongcloud.com/v2/saas/anti_fraud/img";
		$access_key = 'ddFTSqFqoz9tmvqi48Fx';
		$uid = request()->user()->id;
		$filename = '../files/demo.png';

		$payload = array(	
		    'accessKey' => $access_key,
		    'type' => 'POLITICS_PORN_AD_BEHAVIOR',
		    'appId' => 'default',
		    'data' => array(
		        'img' => base64_encode(file_get_contents($res)),
		        'tokenId' => $uid,
		    ),
		);
		$client = new Client();
		$response = $client->request('POST',$url, $payload);
		$result = $response->getBody()->getContents();
    	$result = json_decode($result,true);
    	dd($result);
		*/

		$authUrl = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=PlUPqAtJ1EqwBtD7ggwdpQOS&client_secret=3VKL6R5cgIrljUIHerbuIpJVVIPEgYA9&grant_type=client_credentials";
		$tokenParams = [
			'headers' => [
		        'Content-Type: application/json',
                'Accept: application/json'
		    ],
		    'json' => []

		];
		$client = new Client();
		$tokenResponse = $client->request('POST', $authUrl, $tokenParams);

		$tokenResponse = $tokenResponse->getBody()->getContents();

		$tokenResult = json_decode($tokenResponse,true);
		

		$client = new Client(['Content-Type' => 'application/x-www-form-urlencoded']);
		$apiUrl = "https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token=".$tokenResult['access_token'];

		$params = ["imgUrl"=>$res];
    	
    	$result = $this->run($apiUrl,$params);


    	$result = json_decode($result,true);

    	

    	if($result['conclusionType']==2){

    		//if($result['data']['porn']>0.5){
    			fail('您的图片违规了！');
    		//}

    	}
    	//dd($response->getBody()->getContents());

		return $res;
	}

	public function run($url,$query) {
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_SSL_VERIFYHOST  => false,
            CURLOPT_CUSTOMREQUEST => 'POST',
            
            CURLOPT_POSTFIELDS => $query,
    
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/x-www-form-urlencoded',
                'Accept: application/json'
            ),

        ));
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }
	
	public function upload($image)
	{
		$this->setProperties($image);
		return $this->save();
	}
}
